import React, { useEffect } from 'react'
import { Button, Input, Form } from 'react-vant'
import { Area,Field } from 'react-vant';
import { areaList } from '@vant/area-data'
import { useState } from 'react';
import * as action from "../../action"
import {useNavigate } from "react-router-dom"
import {useDispatch,useSelector} from "react-redux"
import {useLocation} from "react-router-dom"
function Addaddress() {
    const {state} = useLocation()
    const navigate = useNavigate()
    const dispatch = useDispatch()
    const [address,setAddress] = useState("")
    const [value, setValue] = React.useState(['220000', '220300', '220303'])
    const [form] = Form.useForm()
    useEffect(()=>{
      console.log(form,state);
      state && form.setFieldsValue(state)

    },[])
    const onFinish = values => {
   
      // state 如果有代表着是编辑，如果没有就代表着是新增
     
      let needvalue = Object.assign({},values,{address:address})
      if (state) {
       
          needvalue.index = state.index
          console.log(needvalue,"dadasdas");
         dispatch(action.editfn(needvalue))
      } else {
        dispatch(action.addaddress(needvalue)) // 新增
      }
   
      navigate("/home/address")
    }
    const fn = (e,options)=>{
        console.log(e,options);
        let str = ""
        options.forEach(item=>{
            str += item.text

        })
        console.log(str);
        setAddress(str)
    }
  return (
    <div>
        <Form
      form={form}
      onFinish={onFinish}
      footer={
        <div style={{ margin: '16px 16px 0' }}>
          <Button round nativeType='submit' type='primary' block>
            提交
          </Button>
        </div>
      }
    >
      <Form.Item
        tooltip={{
          message:
            'A prime is a natural number greater than 1 that has no positive divisors other than 1 and itself.',
        }}
        intro='确保这是唯一的用户名'
        rules={[{ required: true, message: '请填写用户名' }]}
        name='name'
        label='姓名'
      >
        <Input placeholder='请输入用户名' />
      </Form.Item>
      <Form.Item
        rules={[{ required: true, message: '请填写密码' }]}
        name='phone'
        label='电话'
      >
        <Input placeholder='请输入密码' />
      </Form.Item>
    </Form>
    <Area
      popup={{
        round: true,
      }}
      title='标题'
      value={value}
      areaList={areaList}
      onConfirm={fn}
    >
      {(_, selectRows, actions) => {
        return (
          <Field
            label='选择地区'
            value={selectRows.map(row => row?.text).join(',')}
            onClick={() => actions.open()}
          />
        )
      }}
    </Area>
    </div>
  )
}

export default Addaddress